package com.jinyi.wwdeng.ui.login

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import com.jinyi.base.utils.ActivityStackManager
import com.jinyi.base.utils.BarUtils
import com.jinyi.base.utils.thread.TimingThread
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActLoginBinding
import com.jinyi.wwdeng.pro.ProMvpAct
import com.jinyi.wwdeng.ui.WelcomeAct
import com.jinyi.wwdeng.ui.login.contract.LoginContract
import com.jinyi.wwdeng.ui.login.impl.LoginPresenterImpl
import com.jinyi.wwdeng.ui.privacypolicy.PaPoyAct
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.utils.dialog.LoginDigitalCodeDialog
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/15 15:11
 * @Annotation：注册/登录
 */
class LoginAct : ProMvpAct<LoginContract.View, LoginPresenterImpl>(), LoginContract.View,
    TimingThread.ITimingThreadListener {

    lateinit var binding: ActLoginBinding

    //验证码Dialog
    var mDialog: LoginDigitalCodeDialog? = null

    //倒计时
    var count = 60
    private var timeThread: TimingThread? = null

    override fun getRootView(): View {
        binding = ActLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): LoginPresenterImpl {
        return LoginPresenterImpl()
    }


    @SuppressLint("SetTextI18n")
    override fun initView() {
        setTitleBarVisibility(View.GONE)
        initPresenter()
        //关闭当前页面以外的所有页面
        ActivityStackManager.finishAllActivity(LoginAct::class.java)

        binding.parentLayout.setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
        checkNextBtnState()
        //不显示联系客服图标
        binding.ivKefu.visibility = View.INVISIBLE
        //时区区号
        binding.tvZoneCode.text =
            "+${AppConfigs.getSPString(AppConfigs.SP_KEY.SP_HENECREDIT_TIMEZONE_CODE)}"
    }

    override fun initListener() {
        //客服
        binding.ivKefu.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER, "Login Page")
        }

        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextBtnState()
                if (getMobile().isNotEmpty()) {
                    binding.editMobile.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD))
                } else {
                    binding.editMobile.setTypeface(
                        Typeface.create(
                            Typeface.DEFAULT,
                            Typeface.NORMAL
                        )
                    )
                }
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }
        //电话号码输入框焦点监听
        binding.editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                TrackEventUtils.logEvent(TrackEventType.FORM.FORM_LOGIN_MOBILE, getMobile())
            }
        }

        //隐私政策切换
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            checkNextBtnState()
            when (isChecked) {
                true -> {
                    TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_LOGIN_PRIVACY_AGREE, "")
                }

                false -> {
                    TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_LOGIN_PRIVACY_DENY, "")
                }
            }
        }

        //Next
        binding.btnNext.setOnClickListener {
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_LOGIN_NEXT, "")
            binding.editMobile.clearFocus()
            sendSmsClickAction(true)
        }

        // Privacy policy
        binding.privacyPolicy.setOnClickListener {
            onIntent(PaPoyAct::class.java)
        }
    }

    override fun initData() {
        binding.tvLimitAmount.text = getHomeAmount()
    }

    /**
     * 获取默认账号
     */
    private fun getHomeAmount(): String {
        var homeAmount = "300000"
        val data = JSONObject(AppConfigs.getSPString(AppConfigs.SP_KEY.SP_HENECREDIT_COMMON))
        val customizeObj = data.optJSONObject("customize")
        if (customizeObj != null) {
            homeAmount = customizeObj.optString("homeAmount", "300000")
        }
        return homeAmount
    }

    /**
     * 验证码发送成功
     */
    override fun showSendSmsSuccess(data: JSONObject) {
        showDigitalDialog()
    }

    /**
     * 登录成功
     */
    override fun showLoginSuccess() {
        //保存手机号码，个人中心使用
        AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_MOBILE, getMobile())
        //停止倒计时
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        if (mDialog != null) {
            onHideSoftInput(mDialog!!.binding.editCode)
            mDialog!!.dismiss()
        }
        onIntent(WelcomeAct::class.java)
        finish()
    }

    /**
     * 登录失败
     */
    override fun showLoginFailure(data: JSONObject) {
        //停止倒计时
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        if (mDialog != null) {
            //显示验证码错误样式
            mDialog!!.showWrongLayout()
        }
    }

    /**
     * 设置按钮状态
     */
    private fun checkNextBtnState() {
        if (binding.checkBox.isChecked && getMobile().isNotEmpty()) {
            binding.btnNext.setTextColor(ContextCompat.getColor(this, R.color.color_021e00))
            binding.btnNext.setBackgroundResource(R.drawable.base_circle_fill_9fe76f)
            binding.btnNext.isEnabled = true
        } else {
            binding.btnNext.setTextColor(
                ContextCompat.getColor(
                    this,
                    com.jinyi.lib_base.R.color.color_ffffff
                )
            )
            binding.btnNext.setBackgroundResource(R.drawable.base_circle_fill_d0d4dd)
            binding.btnNext.isEnabled = false
        }
    }

    /**
     * 获取手机号码内容
     */
    override fun getMobile(): String {
        return binding.editMobile.text.toString().trim()
    }


    /**
     * 发送验证码
     */
    private fun sendSmsClickAction(needShowLoading: Boolean) {
        if (needShowLoading) {
            showLoading("")
        }
        presenter.sendSmsCodeRequest(getMobile())
    }

    /**
     * 验证码输入框
     */
    private fun showDigitalDialog() {
        if (mDialog == null) {
            mDialog = LoginDigitalCodeDialog(this, object : LoginDigitalCodeDialog.IDialogCallback {
                //点击操作监听
                override fun onClick(view: View?) {
                    when (view!!.id) {
                        R.id.ivClose -> {//关闭
                            if (timeThread != null) {
                                timeThread!!.stopThread()
                            }
                            mDialog!!.dismiss()
                        }

                        R.id.resendLayout -> {//重发
                            sendSmsClickAction(false)
                            TrackEventUtils.logEvent(
                                TrackEventType.CLICK.CLICK_LOGIN_VERIFY_CODE_RESEND,
                                ""
                            )
                        }

                        R.id.ivRefresh -> {//刷新
                            sendSmsClickAction(false)
                            TrackEventUtils.logEvent(
                                TrackEventType.CLICK.CLICK_LOGIN_VERIFY_CODE_REFRESH,
                                ""
                            )
                        }
                    }
                }

                //输入完成监听
                override fun inputComplete(content: String) {
                    TrackEventUtils.logEvent(TrackEventType.FORM.FORM_LOGIN_VARIFY_CODE, content)
                    presenter.loginRequest(getMobile(), content)
                }
            })
            mDialog!!.setCancelable(false)
            mDialog!!.setCanceledOnTouchOutside(false)
        }
        if (!mDialog!!.isShowing) {
            mDialog!!.show()
            mDialog!!.setMobile(getMobile())
            mDialog!!.showCountdownLayout(count)
        }
        startTimeThread()
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        count = 60
        mDialog!!.showCountdownLayout(count)
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    //倒计时
    override fun onLoading() {
        if (count <= 1) {
            count = 60
            timeThread!!.stopThread()
            mDialog!!.showRefreshLayout()
            return
        }
        count--
        mDialog!!.onRefreshCountdown(count)
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_LOGIN_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_LOGIN_END, "")
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
        if (mDialog != null) {
            mDialog = null
        }
    }
}